package de.slothsoft.network;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;

@SuppressWarnings("nls")
public class ServerPanel extends AbstractNetworkPanel {

	private static final long serialVersionUID = 1L;

	private Server server;

	@Override
	protected void createTopControls(JPanel parent) {
		setBorder(BorderFactory.createTitledBorder("Server"));

		parent.setLayout(new FlowLayout(FlowLayout.LEFT));

		final JButton startButton = new JButton("Starten");
		parent.add(startButton);

		final JButton stopButton = new JButton("Stoppen");
		stopButton.setEnabled(false);
		parent.add(stopButton);

		startButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					startServer();
					startButton.setEnabled(false);
					stopButton.setEnabled(true);
				} catch (NetworkException e) {
					e.printStackTrace(getOutputStream());
					startButton.setEnabled(true);
					stopButton.setEnabled(false);
				}
			}
		});
		stopButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					stopServer();
				} catch (NetworkException e) {
					e.printStackTrace(getOutputStream());
				}
				startButton.setEnabled(true);
				stopButton.setEnabled(false);
			}
		});

	}

	protected void startServer() throws NetworkException {
		this.server = new BroadcastingServer(NetworkTest.PORT) {
			@Override
			protected void broadcastObject(Client source, Object object) throws IOException {
				getOutputStream().println("Sende Nachricht an alle: " + object);
				super.broadcastObject(source, object);
			}
		};
		this.server.addServerListener(new ServerListener() {

			@Override
			public void clientDisconnected(ServerEvent event) {
				getOutputStream().println("Client wurde getrennt.");
			}

			@Override
			public void clientConnected(ServerEvent event) {
				getOutputStream().println("Client hat sich verbunden.");
			}
		});
		getOutputStream().println("Server gestarted.");
		this.server.start();
	}

	protected void stopServer() throws NetworkException {
		if (this.server != null) {
			this.server.stopServer();
		}
	}

}
